package org.springframework.boot.autoconfigure.mock.strategy;

import org.springframework.boot.autoconfigure.mock.model.MockResMeta;
import org.springframework.boot.autoconfigure.mock.model.MockResTypeEnum;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author: hooware
 * @Date: 2021/12/26 18:15
 * @Description:
 */
public class MethodValueMockResProcessor implements IMockResProcessor {

    @Override
    public boolean match(MockResTypeEnum mockResTypeEnum) {
        return MockResTypeEnum.METHOD.equals(mockResTypeEnum);
    }

    @Override
    public Object mockProcess(MockResMeta mockResMeta) throws ReflectiveOperationException {
        // 1.执行注解用户指定的方法
        for (Method method : mockResMeta.getClazz().getDeclaredMethods()) {
            if (method.getName().equals(mockResMeta.getMethod())) {
                method.setAccessible(true);
                if (CollectionUtils.isEmpty(Arrays.asList(mockResMeta.getParams()))) {
                    return method.invoke(mockResMeta.getClazz().newInstance());
                } else {
                    return method.invoke(mockResMeta.getClazz().newInstance(), (Object[]) mockResMeta.getParams());
                }
            }
        }
        // 2.不符合策略条件时默认返回null进行handler兜底
        return null;
    }
}
